package com.atwisdom.star.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.JsonUtil;
import com.atwisdom.star.common.vo.ActionData;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.core.bsl.modelClass.resource.Impl.ResourceInstanceBslServiceImpl;
import com.atwisdom.star.core.bsl.modelClass.resource.Impl.ResourceModelBslServiceImpl;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.atwisdom.star.log.aop.StarAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/resourceTenant")
public class ResourceTenantController {
    private ResourceModelBslServiceImpl resourceModelBslService;
    private ResourceInstanceBslServiceImpl resourceInstanceBslService;

    @Autowired
    public void setResourceModelBslService(ResourceModelBslServiceImpl resourceModelBslService) {
        this.resourceModelBslService = resourceModelBslService;
    }

    @Autowired
    public void setResourceInstanceBslService(ResourceInstanceBslServiceImpl resourceInstanceBslService) {
        this.resourceInstanceBslService = resourceInstanceBslService;
    }

    /**
     * @param actionDataList 接收参数据
     * @return 返回结果
     * @throws BusinessException 异常
     */
    @StarAnnotation
    @PostMapping(value = "/instance")
    public ResultInfo resourceInstance(@RequestBody List<ActionData<JSONObject>> actionDataList) throws BusinessException {
        ResultInfo resultInfo = resourceInstanceBslService.responseFactory(actionDataList);
        Object data = resultInfo.getData();
        if (data instanceof List) {
            JSONArray jsonArray = JsonUtil.toJSONArray(data);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                JSONObject values = jsonObject.getJSONObject("values");
                if (values != null) {
                    values.forEach((k,v)->{
                        if (k.contains("assword")) {
                            values.put(k, "******");
                        }
                    });
                }
            }
            resultInfo.setData(jsonArray);
        }
        return resultInfo;
    }
}
